/*
 * Copyright (c) zhg2yqq.com Corp.
 * All Rights Reserved.
 */
package com.zhg2yqq.wheels.mvc.plugin;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;

import com.zhg2yqq.wheels.mvc.util.FieldEncryptUtil;

/**
 * 注解字段加密
 *
 * @author zhg2yqq, 2022年12月3日
 * @version zhg2yqq v1.0
 */
@Intercepts({
        // type 指定代理对象，method 指定代理方法，args 指定type代理类中method方法的参数
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class,
                Object.class})})
public class FieldEncryptInterceptor implements Interceptor {
    private String encryptKey;

    public FieldEncryptInterceptor() {
    }

    public FieldEncryptInterceptor(String encryptKey) {
        this.encryptKey = encryptKey;
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement statement = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType type = statement.getSqlCommandType();
        if (SqlCommandType.INSERT.equals(type) || SqlCommandType.UPDATE.equals(type)) {
            Object parameter = invocation.getArgs()[1];
            FieldEncryptUtil.encryptField(encryptKey, parameter);
            Object result = invocation.proceed();
            FieldEncryptUtil.decryptField(encryptKey, parameter);
            return result;
        }
        return invocation.proceed();
    }
}
